import React, {useReducer, useRef, useState} from "react";
import {View, Text, Button} from "@tarojs/components";
import Taro from "@tarojs/taro";
import Webcam from 'webcam-easy';

let webcam = undefined;

export default function TestWebCam(props) {

  const webcamElementRef = useRef(undefined)
  const canvasElementRef = useRef(undefined)
  const snapSoundElementRef = useRef(undefined)

  function onWebCamStart() {
    webcam = new Webcam(webcamElementRef.current, 'user', canvasElementRef.current, snapSoundElementRef.current);

    webcam.start()
      .then(result =>{
        console.log("webcam started", result);
      })
      .catch(err => {
        console.log(err);
      });
  }
  function onTakePhoto() {
    const picture = webcam?.snap();
    console.log(picture);
  }

  function onWebCamSop() {
    webcam?.stop();
  }

  return(
    <View>
      <View>TestWebCam</View>

      <video ref={webcamElementRef} style={{width:"640", height:"480"}}></video>
      <canvas ref={canvasElementRef} ></canvas>
      <audio ref={snapSoundElementRef} ></audio>

      <Button onClick={onWebCamStart}>Start WebCam</Button>
      <Button onClick={onTakePhoto}>Take Photo</Button>
      <Button onClick={onWebCamSop}>Stop WebCam</Button>

    </View>
  )
}
